package com.epro.dx.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Point;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.ScrollView;

import com.epro.dx.R;
import com.epro.dx.activity.HomeActivity;
import com.epro.dx.activity.HomeActivity.OnTouchEventListenner;
import com.epro.dx.activity.LoginActivity;
import com.epro.dx.activity.ProductListActivity;
import com.epro.dx.activity.coupon.CouponActivity;
import com.epro.dx.activity.filter.FilterActivity;
import com.epro.dx.activity.messagecenter.MessageCenterActivity;
import com.epro.dx.activity.messagecenter.MessagesAndPromotionsListActivity;
import com.epro.dx.activity.search.SearchActivity;
import com.epro.dx.adapter.HomeAdvertisementAdapter;
import com.epro.dx.adapter.HomeBannerAdapter;
import com.epro.dx.adapter.HomeBannerAdapter.onLinkBannerClickListenner;
import com.epro.dx.adapter.ProductListAdapter;
import com.epro.dx.enable.NetworkBroadcastReceiver;
import com.epro.dx.enable.NetworkBroadcastReceiver.NetWorkCallBack;
import com.epro.dx.indicator.IconPageIndicator;
import com.epro.dx.indicator.PageIndicator;
import com.epro.dx.listenner.HotWordsAsyncTaskListenner;
import com.epro.dx.listenner.MyAsyncTaskListenner;
import com.epro.dx.pullview.PullToRefreshBase;
import com.epro.dx.pullview.PullToRefreshBase.Mode;
import com.epro.dx.pullview.PullToRefreshBase.OnRefreshListener2;
import com.epro.dx.pullview.PullToRefreshScrollView;
import com.epro.dx.task.GetHomeBannerAsyncTask;
import com.epro.dx.task.GetOneKeyFilterSettingsAsyncTask;
import com.epro.dx.task.GetProductsFromSkusAsyncTask;
import com.epro.dx.task.GetRecommendTask;
import com.epro.dx.task.GetRecommendTask.GetRecommendsModel;
import com.epro.dx.task.GetTopCategoryAsyncTask;
import com.epro.dx.task.HotWordsAsyncTask;
import com.epro.dx.task.SaveOneKeyFilterStateAsyncTask;
import com.epro.dx.util.ActivityUtil;
import com.epro.dx.util.AsyncTaskUtil;
import com.epro.dx.util.BannerUtils;
import com.epro.dx.util.ImageLoaderUtils;
import com.epro.dx.util.OnekeyFilterLocalUtil;
import com.epro.dx.widget.BottomBtn;
import com.epro.dx.widget.EditTextWithClear;
import com.epro.dx.widget.HorizontalListView;
import com.epro.dx.widget.MyFilterSwitch;
import com.epro.dx.widget.MyFilterSwitch.MyFilterSwitchOnclickListenner;
import com.epro.dx.widget.MyGridView;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.weipu.common.DXApplication;
import com.weipu.common.DXApplication.TrackerName;
import com.weipu.common.constants.Constant;
import com.weipu.common.constants.ServerConstant;
import com.weipu.common.facade.content.api.HomeModuleDataService;
import com.weipu.common.facade.content.api.HotWordService;
import com.weipu.common.facade.content.api.ProductService;
import com.weipu.common.facade.exception.DxException;
import com.weipu.common.facade.factory.ProviderFactory;
import com.weipu.common.facade.model.CatelogModel;
import com.weipu.common.facade.model.HomeDataModel;
import com.weipu.common.facade.model.HomeModuleModel;
import com.weipu.common.facade.model.ModuleChildrenModel;
import com.weipu.common.facade.model.OneKeyFilterResponseModel;
import com.weipu.common.facade.model.Parmars;
import com.weipu.common.facade.model.ProductModel;
import com.weipu.common.facade.model.SearchModel;
import com.weipu.common.observer.MessageObServer;
import com.weipu.common.subject.MessageSubjectImpl;
import com.weipu.common.util.AlertToast;
import com.weipu.common.util.Common;
import com.weipu.common.util.JsonFormat;
import com.weipu.common.util.Logger;
import com.weipu.common.util.NetWorkUtil;
import com.weipu.common.util.StringUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 首页
 *
 * @author hjd008
 * @version [版本号, 2015-1-6]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@SuppressLint("NewApi")
@SuppressWarnings("ResourceType")
public class HomeFragment extends BaseFragment implements OnClickListener,
        NetWorkCallBack, OnTouchEventListenner, onLinkBannerClickListenner, MessageObServer {

    private static final String TAG = "HomeFragment";

    private String searchHint = "";

    private String baseHint = "";

    /**
     * Banner轮播时间
     */
    private static final int LOOP_TIME = 2000;

    public static final String HOMEBFDSKULIST = "HomeBfdSkuList";

    int[] bannerIds = {R.drawable.new_arrivals, R.drawable.mvp,
            R.drawable.topseller,R.drawable.us_warehouse,R.drawable.latest_discounts };
    //分别代表NewArrivals  MVP TopSeller US Warehouse LatestDiscount
    int[] activeType = {4, 3, 2, 10,5};

    /**
     * 搜索框
     */
    private EditTextWithClear edtxtSearch;

    private RelativeLayout bannerLayout;

    /**
     * 广告banner
     */
    public ViewPager viewPagerFastSelling;

    private HomeBannerAdapter bannerAdapter;

    private ImageView deflautImage;

    /**
     * 点点点
     */
    private PageIndicator pageIndicator;

    private View rootView;

    private HomeModuleDataService homeModuleDataService;

    private HotWordService hotWordService;

    private PullToRefreshScrollView homeScrollView;

    private FrameLayout loadingBar;

    // 百分点推荐商品列表
    private MyGridView bfdProductList;

    // 一键过滤
    private MyFilterSwitch filterSwitch;
    private RelativeLayout filterSettingBtn;

    // 消息中心
    private RelativeLayout messageCenterLayout;
    // 有新未读消息的时候显示的点
    private View messageCenterRedPoint;
    // 功能去横向ListView
    private HorizontalListView adverthListView;
    /**
     * 百分点产品适配器
     */
    private ProductListAdapter productListAdapter;

    private AnimationSet switchFilterAnimation;

    private ImageView couponView;

    private ImageView activeView;

    private HomeAdvertisementAdapter advertAdapter;

    private Tracker tracker;

    private DisplayImageOptions options;

    /**
     * 百分点产品数据集合
     */
    private List<ProductModel> myBfdProducts = new ArrayList<ProductModel>();

    /**
     * 广告列表数据
     */
    private List<ModuleChildrenModel> bannerModels;
    /**
     * 功能区数据列表
     */
    private List<ModuleChildrenModel> advertModels;
    /**
     * 首页动态数据列表
     */
    private List<HomeModuleModel> homeModuleModels;

    /**
     * @创建：Tony 2016-4-5下午4:59:36
     * @描述：设置一键过滤开关的状态
     */
    private int setOnekeyFilterSwitchAgainTime = 0;

    /**
     * 判断用户是否正在滑动Banner
     */
    private boolean isFilg;

    /**
     * Banner轮播线程是否开启
     */
    private boolean isBannerRun = false;

    /**
     * 当前banner索引 默认选中第一个
     */
    private int curretnBannerIndex = 1;

    private Handler bannerHandler = new Handler();

    // 是否进入onStop 标志是否再次Onresume时 启动BannerLoopRunable
    private boolean isStop;

    // // 是否切换小图片的背景设置
    // private boolean isHome = true;
    // 判断是否第一次创建fragment后已经加载了数据
    private boolean isCreateView;
    private ArrayList<Integer> skus;
    HomeActivity homeActivity;
    /**
     * 热搜词汇Task
     */
    private HotWordsAsyncTask hotWordsAsyncTask = null;

    private Handler uiHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == 0) {
                edtxtSearch.setHint(searchHint);
            }
        }

        ;
    };
    /**
     * 首页轮转Banner线程
     */
    private Runnable bannerLoopRunnable = new Runnable() {

        @Override
        public void run() {
            if (!isFilg) {
                if (null != bannerModels && bannerModels.size() != 0
                        && viewPagerFastSelling != null) {
//					int max = bannerModels.size() + 1;
                    int index = curretnBannerIndex++ % bannerModels.size();
                    viewPagerFastSelling.setCurrentItem(index, true);
//					if(index==max){
//						viewPagerFastSelling.setCurrentItem(1,false);
//					}
                    bannerHandler.postDelayed(bannerLoopRunnable, LOOP_TIME);
                } else {
                    isBannerRun = false;
                }
            }

        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // 集成GA测量
        tracker = ((DXApplication) getActivity().getApplication())
                .getTracker(TrackerName.APP_TRACKER);
        if (null == rootView) {
            rootView = LayoutInflater.from(getActivity()).inflate(
                    R.layout.fragment_home, null);
            initView();
            setListenner();
            initAnimation();
            //注册消息观察者
            MessageSubjectImpl.getMessageSubjectImplInstance().attach(this);
            // bannerService = ProviderFactory.createBannerServiceDBProvider();
            homeModuleDataService = ProviderFactory
                    .createHomeModuleDataServiceDBProvider();
            hotWordService = ProviderFactory.createHotWordServiceDBProvider();
            options = ImageLoaderUtils.getImageLoaderOptions(
                    R.drawable.item_default, R.drawable.item_default);
        }
        ActivityUtil.setStatusColor(getActivity(), 0, rootView);
//        AsyncTaskUtil.executeTask(new HomeDataCacheTask());
        AsyncTaskUtil.executeTask(new HomeDataAsyncTask());
        AsyncTaskUtil.executeTask(hotWordsAsyncTask);
        isCreateView = true;
        NetworkBroadcastReceiver.setCallBack(this);
        setAdvertDefaultData();
        setAdapter();
        //先获取本地数据库存储的数据
        getBfdLocalData();
        getBfdProducts();
        // 设置一键过滤开关状态
        setOnekeyFilterSwitch();
        return rootView;
    }

    /**
     * 初始化控件及
     */
    private void initView() {
        hotWordsAsyncTask = new HotWordsAsyncTask(getActivity(), new HotWordsAsyncTaskListenner() {

            @Override
            public void onPreTask() {

            }

            @Override
            public void onPostTask(String result, Object obj) {
                if ("0".equals(result)) {
                    String[] hotWords = (String[]) obj;
                    StringBuilder stringHint = new StringBuilder(baseHint);
                    for (int i = 0; i < hotWords.length; i++) {
                        if (i == 0) {
                            stringHint.append(" " + hotWords[i]);
                        } else {
                            stringHint.append(",").append(hotWords[i]);
                        }
                    }
                    searchHint = stringHint.toString();
                    edtxtSearch.setHint(searchHint);
                }
            }

            @Override
            public void onFinishSomeTask(Object obj) {
                String[] hots = (String[]) obj;
                if (null != hots) {
                    StringBuilder stringHint = new StringBuilder(baseHint);
                    for (int i = 0; i < hots.length; i++) {
                        if (i == 0) {
                            stringHint.append(" " + hots[i]);
                        } else {
                            stringHint.append(",").append(hots[i]);
                        }
                    }
                    searchHint = stringHint.toString();
                    uiHandler.sendEmptyMessage(0);
                }
            }
        });
        baseHint = getActivity().getString(R.string.search_hint);
        bannerLayout = (RelativeLayout) rootView
                .findViewById(R.id.banner_Layout);
        setBannerSize();
        homeScrollView = (PullToRefreshScrollView) rootView
                .findViewById(R.id.home_layout);
        adverthListView = (HorizontalListView) rootView
                .findViewById(R.id.advertisement_hlist);
        loadingBar = (FrameLayout) rootView.findViewById(R.id.loading_progress);

        couponView = (ImageView) rootView
                .findViewById(R.id.homefragment_coupon);

        activeView = (ImageView) rootView
                .findViewById(R.id.homefragment_single_activity);

        bfdProductList = (MyGridView) rootView
                .findViewById(R.id.bfd_product_list);
        // bannerContainer = (LinearLayout) rootView
        // .findViewById(R.id.ll_banners_container);

        edtxtSearch = (EditTextWithClear) rootView
                .findViewById(R.id.edtxt_search);
        edtxtSearch.setFocusable(false);
        edtxtSearch.isNeedShowClearBtn(false);

        viewPagerFastSelling = (ViewPager) rootView
                .findViewById(R.id.vp_fastselling);
        viewPagerFastSelling.setVisibility(View.GONE);
        deflautImage = (ImageView) rootView.findViewById(R.id.default_img);
        // 对于手动创建的ViewPager,必须调用setId()方法设置一个id
        viewPagerFastSelling.setId(100);
        pageIndicator = (IconPageIndicator) rootView
                .findViewById(R.id.indicator);
        // edtxtSearch.setOnEditorActionListener(new OnEditorActionListener() {
        //
        // public boolean onEditorAction(TextView v, int actionId,
        // KeyEvent event) {
        // if (actionId == EditorInfo.IME_ACTION_SEARCH) {
        // searchlist();
        // }
        // return false;
        // }
        // });

        homeScrollView.setMode(Mode.PULL_FROM_START);

        // 一键过滤按钮
        filterSwitch = (MyFilterSwitch) rootView
                .findViewById(R.id.homefragment_filter_switch);
        filterSettingBtn = (RelativeLayout) rootView
                .findViewById(R.id.btn_home_filter_setting);

        // 百分点推荐栏头部标题隐藏
        rootView.findViewById(R.id.bfd_tab_title).setVisibility(View.GONE);
        rootView.findViewById(R.id.homefragment_bfd_more).setOnClickListener(this);

        // 消息中心
        messageCenterLayout = (RelativeLayout) rootView
                .findViewById(R.id.homefragment_message);

        messageCenterRedPoint = rootView
                .findViewById(R.id.homefragment_message_point);
    }

    /**
     * 设置控件事件监听
     */
    private void setListenner() {
        couponView.setOnClickListener(this);
        activeView.setOnClickListener(this);
        adverthListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1,
                                    int position, long arg3) {
                ModuleChildrenModel moduleCModel = advertModels.get(position);
//				Log.i("FFF", "onItemClick "+moduleCModel.getActiveType());
                BannerUtils.clickActiv(homeActivity, moduleCModel, Parmars.GETTYPE_HOMEACTIVE, null);
            }
        });
        edtxtSearch.setOnClickListener(this);
        homeScrollView
                .setOnRefreshListener(new OnRefreshListener2<ScrollView>() {
                    @Override
                    public void onPullDownToRefresh(
                            PullToRefreshBase<ScrollView> refreshView) {
                        AsyncTaskUtil.executeTask(new HomeDataAsyncTask());
                        getBfdProducts();
                    }

                    @Override
                    public void onPullUpToRefresh(
                            PullToRefreshBase<ScrollView> refreshView) {
                    }
                });
        filterSettingBtn.setOnClickListener(this);
        filterSwitch
                .setMyFilterSwitchOnclickListenner(new MyFilterSwitchOnclickListenner() {

                    @Override
                    public void onMyFilterSwitchClick() {
                        // TODO
                        if (ActivityUtil.isLogin(getActivity())) {
                            //调用接口保存当前用户状态
                            AsyncTaskUtil.executeTask(new SaveOneKeyFilterStateAsyncTask(getActivity(), filterSwitch.getSwitchState(), new MyAsyncTaskListenner() {

                                @Override
                                public void onPreTask() {
                                    showWaitingDialog();
                                }

                                @Override
                                public void onPostTask(String result, Object obj) {
                                    // TODO
                                    hideWaitingDialog();
                                    if ("0".equals(result)) {//成功了，保存状态到本地
                                        StringUtil.saveConfig(ActivityUtil.getCustomerID() + ServerConstant.OneKeyFilter.ISFILTERKEY_ONLINE, "" + filterSwitch.getSwitchState());
                                        startFilterModeChangeAnima();
                                    } else {//失败，设置回原来的状态
                                        filterSwitch.setSwitchState("true".equals(StringUtil.getConfig(ActivityUtil.getCustomerID() + ServerConstant.OneKeyFilter.ISFILTERKEY_ONLINE, "false")));
                                        AlertToast.alert(getActivity(), ServerConstant.ReturnCode.MESSAGEMAP.get(result));
                                    }
                                }
                            }));
                        } else {//没有登陆，更新本地状态存储
                            StringUtil.saveConfig(ServerConstant.OneKeyFilter.ISFILTERKEY_LOCAL, "" + filterSwitch.getSwitchState());
                            startFilterModeChangeAnima();
                        }
                    }
                });
        messageCenterLayout.setOnClickListener(this);
    }


    /**
     * 设置初始值
     */
    private void setInitData() {
        if (null == homeModuleModels) {
            // 首页预先判断网络是否可用
            if (NetWorkUtil.isNetworkAvailable(getActivity())) {
                AsyncTaskUtil.executeTask(new HomeDataAsyncTask());
            } else {
                loadingBar.setVisibility(View.GONE);
                AlertToast.alert(getActivity(),
                        R.string.client_net_un_available);
            }
        }

        // 加载显示百分点推荐数据
//		getBfdProducts();

        // 设置一键过滤开关状态
        setOnekeyFilterSwitch();
    }

    /**
     * 设置数据适配器
     */
    private void setAdapter() {
        // 功能区 适配器
        advertAdapter = new HomeAdvertisementAdapter(getActivity(),
                advertModels);
        adverthListView.setAdapter(advertAdapter);

        // 百分点适配器
        productListAdapter = new ProductListAdapter(getActivity(),
                myBfdProducts, false, getDensityDpi(),
                ((HomeActivity) getActivity()).tracker);
        bfdProductList.setAdapter(productListAdapter);
    }

    /**
     * 首页一键切换动画
     */
    private void initAnimation() {
        switchFilterAnimation = new AnimationSet(false);
        final AnimationSet aEnd = new AnimationSet(false);

        Animation animation = AnimationUtils.loadAnimation(getActivity(),
                R.anim.shake_home);
        switchFilterAnimation.addAnimation(animation);

        switchFilterAnimation.setAnimationListener(new AnimationListener() {

            @Override
            public void onAnimationStart(Animation animation) {
                //更新一级目录本地数据库缓存
                AsyncTaskUtil.executeTask(new GetTopCategoryAsyncTask(getActivity(), null));
                //更新推荐数据
                getBfdProducts();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
                // TODO

            }

            @Override
            public void onAnimationEnd(Animation animation) {
            }
        });
    }

    /**
     * 获取屏幕密度
     *
     * @return
     */
    protected int getDensityDpi() {
        DisplayMetrics metrics = new DisplayMetrics();
        Display display = getActivity().getWindowManager().getDefaultDisplay();
        display.getMetrics(metrics);
        return metrics.densityDpi;
    }

    /**
     * 设置轮转Banner的显示大小
     */
    private void setBannerSize() {
        Point screenPoint = ActivityUtil.getScreenSize(getActivity());
        int screenWidth = screenPoint.x;
        int bannerHeight = (int) (screenWidth / 2.5)
                + (int) (screenWidth % 2.5);
        LayoutParams params = new LayoutParams(screenWidth, bannerHeight);
        bannerLayout.setLayoutParams(params);
    }

    /**
     * 控制首页刷新及Banner轮转定时器
     */
    private void titleAndBannerSet() {
        // setTitleloginView();
        if (null != rootView) {
            if (null != homeModuleModels && !homeModuleModels.isEmpty()
                    && viewPagerFastSelling.getVisibility() == View.GONE) {
                // processFastSelling();
                // refreshHomeUi(homeModuleModels,"onResume");
            }

        }
        if (!isBannerRun && isStop) {
            isBannerRun = true;
            Logger.i(TAG, "to start onResume");
            bannerHandler.postDelayed(bannerLoopRunnable, LOOP_TIME);
        }
        isStop = false;
    }


    /**
     * 设置功能区设置默认值
     */
    private void setAdvertDefaultData() {
        if (null == advertModels) {
            advertModels = new ArrayList<ModuleChildrenModel>();
        }
        for (int i = 0; i < activeType.length; i++) {
            ModuleChildrenModel mcModel = new ModuleChildrenModel();
            mcModel.setActiveType(activeType[i]);
            mcModel.setResId(bannerIds[i]);
            mcModel.setDefault(true);
            //Client=5, 客户端自定义
            mcModel.setLinkType(5);
            advertModels.add(mcModel);
        }
    }


    /**
     * 一件过滤功能
     */
    private void setOnekeyFilterSwitch() {
        String config = null;
        if (ActivityUtil.isLogin(getActivity())) {
            config = StringUtil.getConfig(ActivityUtil.getCustomerID()
                    + ServerConstant.OneKeyFilter.ISFILTERKEY_ONLINE, null);
            if (null == config && setOnekeyFilterSwitchAgainTime < 1) {// 出现异常，执行获取一键过滤状态的接口
                AsyncTaskUtil.executeTask(new GetOneKeyFilterSettingsAsyncTask(
                        getActivity(), new MyAsyncTaskListenner() {

                    @Override
                    public void onPreTask() {
                    }

                    @Override
                    public void onPostTask(String result, Object obj) {
                        setOnekeyFilterSwitch();
                        ++setOnekeyFilterSwitchAgainTime;
                    }
                }));
            }
        } else {
            config = StringUtil.getConfig(
                    ServerConstant.OneKeyFilter.ISFILTERKEY_LOCAL, null);
        }
        filterSwitch.setSwitchState("true".equals(config) ? true : false);
    }

    /**
     * 加载显示百分点推荐数据
     */
    private void getBfdProducts() {
        Map<String, String> params = new HashMap<String, String>();
        AsyncTaskUtil.executeTask(new GetRecommendTask(ActivityUtil.getCustomerID(), 1, new MyAsyncTaskListenner() {

            @Override
            public void onPreTask() {
                // TODO Auto-generated method stub

            }

            @Override
            public void onPostTask(String result, Object obj) {

//              Log.d("BFD",
//                      recommendRequestId + ">>" + json.toString());
                // 获取SKU列表，调用接口获取商品列表信息展示
                if (!"0".equals(result)) {
                    return;
                }
                GetRecommendsModel model = (GetRecommendsModel) obj;
                if (model.IsSuccess && model.Skus != null) {
                    String[] splits = model.Skus.split(",");
                    skus = new ArrayList<Integer>();
                    for (int i = 0; i < splits.length; i++) {
                        skus.add(Integer.parseInt(splits[i]));
                    }

                    if (skus.size() > 0) {
                        AsyncTaskUtil
                                .executeTask(new GetProductsFromSkusAsyncTask(
                                        skus, getActivity(), 0, 20, Constant.SORT_POPULARITY,
                                        -2, OnekeyFilterLocalUtil.getFilterState(getActivity()), new MyAsyncTaskListenner() {

                                    @Override
                                    public void onPreTask() {

                                    }

                                    @SuppressWarnings("unchecked")
                                    @Override
                                    public void onPostTask(
                                            String result,
                                            Object bfdProducts) {
                                        ArrayList<ProductModel> mBfdProducts = (ArrayList<ProductModel>) bfdProducts;
                                        if ("0".equals(result)
                                                && bfdProducts != null
                                                && mBfdProducts
                                                .size() > 0) {
                                            StringUtil.saveConfig("Home_RefreshBFD", "false");
                                            //将获取到的推荐数据保存到数据库中
                                            saveRecommendProducts2LocalData(mBfdProducts);
                                            // 显示推荐商品列表
                                            myBfdProducts
                                                    .clear();
                                            myBfdProducts
                                                    .addAll(mBfdProducts);
                                            productListAdapter
                                                    .setCurrencyCode(
                                                            mBfdProducts
                                                                    .get(0)
                                                                    .getCurrencyCode(),
                                                            mBfdProducts
                                                                    .get(0)
                                                                    .getCurrencyCodeSymbol());
                                            productListAdapter
                                                    .setRecommendRequestId("");
                                            productListAdapter
                                                    .notifyDataSetChanged();
                                        } else {
                                            // 显示Topsellers前20个数据
//                                                  if(null==myBfdProducts || myBfdProducts.size()==0)
                                            {
                                                getTopSellersProducts();
                                            }
                                        }
                                    }
                                }));
                    } else {
                        // 显示Topsellers前20个数据
//                      if(null==myBfdProducts || myBfdProducts.size()==0)
                        {
                            getTopSellersProducts();
                        }
                    }
                } else {
                    // 显示Topsellers前20个数据
//                  if(null==myBfdProducts || myBfdProducts.size()==0)
                    {
                        getTopSellersProducts();
                    }
                }

            }
        }));
    }

    /**
     * @创建：Tony 2016-5-13下午1:40:26
     * @描述：获取本地保存的推荐数据，优先显示出来
     */
    private void getBfdLocalData() {
        AsyncTaskUtil.executeTask(new AsyncTask<Void, Void, String>() {

            ArrayList<ProductModel> products;

            @Override
            protected String doInBackground(Void... params) {
                products = ProviderFactory.createProductDBProvider().queryProductListByType(ProductService.TYPE_BFD_HOME);
                return "0";
            }

            @Override
            protected void onPostExecute(String result) {
                if (null != products && products.size() > 0) {
                    myBfdProducts.clear();
                    myBfdProducts.addAll(products);
                    productListAdapter
                            .setCurrencyCode(
                                    myBfdProducts
                                            .get(0)
                                            .getCurrencyCode(),
                                    myBfdProducts
                                            .get(0)
                                            .getCurrencyCodeSymbol());
                    productListAdapter.notifyDataSetChanged();
                }
            }
        });
    }

    /**
     * 用于在没有推荐数据时显示TopSellors数据
     */
    private void getTopSellersProducts() {
        AsyncTaskUtil.executeTask(new GetHomeBannerAsyncTask(getActivity(), 1,
                Constant.LIST_PAGE_COUNT, OnekeyFilterLocalUtil.getFilterState(getActivity()), -2, Constant.TYPE_TOPSELLERS,
                Constant.SORT_POPULARITY, new MyAsyncTaskListenner() {

            @Override
            public void onPreTask() {
            }

            @Override
            public void onPostTask(String result, Object obj) {
                // TODO Auto-generated method stub
                SearchModel mSearchModel = (SearchModel) obj;
                if ("0".equals(result) && null != mSearchModel
                        && mSearchModel.getProductModels().size() > 0) {
                    myBfdProducts.clear();
                    myBfdProducts.addAll(mSearchModel
                            .getProductModels());
                    productListAdapter.setCurrencyCode(
                            mSearchModel.getCurrencyCode(),
                            mSearchModel.getCurrencyCodeSymbol());
                    productListAdapter.notifyDataSetChanged();
                }
            }
        }));
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            NetworkBroadcastReceiver.setCallBack(this);
            Logger.i(TAG, "onHiddenChanged " + isCreateView + " " + rootView
                    + isCreateView);
            if (!isCreateView) {
                setInitData();
            } else {
                isCreateView = false;
            }
            titleAndBannerSet();
            // AsyncTaskUtil.executeTask(new HomeDataAsyncTask());
            if ("true".equals(StringUtil.getConfig("Home_RefreshBFD", "false"))) {
                getBfdProducts();
            }
        } else {
            NetworkBroadcastReceiver.setCallBack(null);
            isStop = true;
            bannerHandler.removeCallbacks(bannerLoopRunnable);
            isBannerRun = false;
        }
    }

    @Override
    public void onResume() {
        if (!this.isHidden()) {
            NetworkBroadcastReceiver.setCallBack(this);
            titleAndBannerSet();
            setOnekeyFilterSwitch();
            if ("true".equals(StringUtil.getConfig("Home_RefreshBFD", "false"))) {
                getBfdProducts();
            }
        }
        //更新未读消息状态
        String unMsg = StringUtil.getConfig(getActivity(), ServerConstant.MessageCenter.UNREAD_MESSAGE);
        boolean isNotRead = Boolean.parseBoolean(unMsg);
        if (isNotRead) {
            setMessageState(1);
        } else {
            setMessageState(0);
        }
        super.onResume();
    }

    @Override
    public void onPause() {
        NetworkBroadcastReceiver.setCallBack(null);
        super.onPause();
    }

    @Override
    public void onDestroy() {
        MessageSubjectImpl.getMessageSubjectImplInstance().remove(this);
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.edtxt_search:
                Intent searchIntent = new Intent(getActivity(),
                        SearchActivity.class);
                startActivity(searchIntent);
                break;

            case R.id.homefragment_coupon: {
                tracker.send(new HitBuilders.EventBuilder("Click Coupon",
                        "CouponMarket").build());
                Intent i = new Intent(getActivity(), CouponActivity.class);
                i.putExtra("pageNumber", 0);
                startActivity(i);
                break;
            }
            case R.id.homefragment_single_activity:
                //点击活动区进入活动列表页 ,访问接口获取活动列表
                Intent intentToActiveListPage = new Intent(getActivity(), MessagesAndPromotionsListActivity.class);
                Bundle bundle = new Bundle();
                bundle.putBoolean(ServerConstant.MessageCenter.ISPROMOTION, true);
                bundle.putInt(ServerConstant.PAGETITLEID, R.string.promotion_list_title);
                bundle.putInt(MessagesAndPromotionsListActivity.FROMTYPE, MessagesAndPromotionsListActivity.FROMTYPE_HOMEACTIV);
                intentToActiveListPage.putExtra(ServerConstant.MessageCenter.INTENT_BUNDLE, bundle);
                startActivity(intentToActiveListPage);
                break;
            case R.id.btn_home_filter_setting: {
                tracker.send(new HitBuilders.EventBuilder("Click Home Title",
                        "FilterSetting").build());
                // 获取用户设置的一键过滤信息:用户登录先判断本地数据库是否有数据，如果没有调用接口获取并保存本地数据库，有数据先取数据跳转页面之后再调用接口更新
                if (ActivityUtil.isLogin(getActivity())) {
                    // 先查询本地数据库
                    OneKeyFilterResponseModel localData = OnekeyFilterLocalUtil
                            .getLocalData(getActivity(),
                                    ActivityUtil.getCustomerID());
                    if (null == localData) {// 本地数据为空，访问接口加载数据
                        AsyncTaskUtil
                                .executeTask(new GetOneKeyFilterSettingsAsyncTask(
                                        getActivity(), new MyAsyncTaskListenner() {

                                    @Override
                                    public void onPreTask() {
                                        showWaitingDialog();
                                        filterSettingBtn
                                                .setClickable(false);
                                    }

                                    @Override
                                    public void onPostTask(String result,
                                                           Object obj) {
                                        hideWaitingDialog();
                                        filterSettingBtn.setClickable(true);
                                        if ("0".equals(result)) {
                                            // 跳转到选择过滤页面
                                            OneKeyFilterResponseModel customerFilter = (OneKeyFilterResponseModel) obj;
                                            gotoFilterSettingsPage(customerFilter);
                                        } else {
                                            AlertToast
                                                    .alert(getActivity(),
                                                            ServerConstant.ReturnCode.MESSAGEMAP
                                                                    .get(result));
                                        }
                                    }
                                }));
                    } else {
                        gotoFilterSettingsPage(localData);
                    }
                } else {// 没有登录，获取本地数据库保存的信息
                    OneKeyFilterResponseModel localData = OnekeyFilterLocalUtil
                            .getLocalData(getActivity(), -1);
                    if (null == localData) {// 本地没有保存的数据，采用默认设置
                        List<CatelogModel> whiteCategorys = OnekeyFilterLocalUtil
                                .turnTopCategorysToWhiteCategorys(getActivity());
                        OneKeyFilterResponseModel model = new OneKeyFilterResponseModel();
                        model.setWhiteCategoryData(whiteCategorys);
                        gotoFilterSettingsPage(model);
                    } else {
                        gotoFilterSettingsPage(localData);
                    }
                }
                break;
            }
            case R.id.homefragment_message:
                //清楚通知栏消息
                NotificationManager manager = (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
                manager.cancelAll();
                // 跳转到消息中心页面,判断是否登陆，没有登陆跳转到登陆页面
                if (ActivityUtil.isLogin(getActivity())) {
                    Intent intent = new Intent(getActivity(),
                            MessageCenterActivity.class);
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(getActivity(),
                            LoginActivity.class);
                    Bundle data = new Bundle();
                    data.putInt(ServerConstant.Parameter.PARAMETER_NAME_LOGIN_ACTION_TYPE,
                            ServerConstant.Parameter.PARAMETER_ACTION_TYPE_MESSAGECENTER);
                    data.putString(HomeActivity.CURRENT_TAB_TAG, BottomBtn.HOME_TAG);
                    intent.putExtras(data);
                    startActivity(intent);
                }
//			setMessageState(0);
                break;
            case R.id.homefragment_bfd_more:
                // 跳转到推荐产品列表页面
                if (null != skus && skus.size() > 0) {
                    Intent intentToProductList = new Intent(getActivity(),
                            ProductListActivity.class);
                    intentToProductList.putExtra(Constant.TO_PRODUCTLIST_FROM, Constant.FROM_HOME_BFD);
                    intentToProductList.putIntegerArrayListExtra(HOMEBFDSKULIST, skus);
                    intentToProductList.putExtra(Constant.PRODUCT_TITLE, getString(R.string.bfd_mayliketab));
                    startActivity(intentToProductList);
                }
                break;
            default:
                break;
        }

    }

    /**
     * 设置Message未读状态
     *
     * @param unReadMsg
     */
    private void setMessageState(int unReadMsg) {
        if (unReadMsg > 0) {
            messageCenterRedPoint.setVisibility(View.VISIBLE);
        } else {
            messageCenterRedPoint.setVisibility(View.GONE);
        }
    }

    /**
     * @param customerFilter
     * @创建：Tony 2016-4-5下午5:43:42
     * @描述：组织数据跳转到一键过滤设置页面
     */
    public void gotoFilterSettingsPage(OneKeyFilterResponseModel customerFilter) {
        Bundle bundle = new Bundle();
        bundle.putParcelableArrayList(
                ServerConstant.OneKeyFilter.WHITECATEGORY,
                (ArrayList<CatelogModel>) customerFilter.getWhiteCategoryData());
        bundle.putParcelableArrayList(
                ServerConstant.OneKeyFilter.BLACKCATEGORY,
                (ArrayList<CatelogModel>) customerFilter.getBlackCategoryData());
        Intent intent = new Intent(getActivity(), FilterActivity.class);
        intent.putExtra(ServerConstant.OneKeyFilter.FILTERBUNDLE, bundle);
        startActivity(intent);
        getActivity().overridePendingTransition(R.anim.push_right_in,
                R.anim.alpha_out_300);
    }

    /**
     * New Arrivals Top Sellers Mvp LatestDiscount点击跳转逻辑
     *
     * @param type
     */
//	public void gotoHomePublicList(String type) {
//		String title = "";
//		if (Constant.TYPE_NEWARRIVALS.equals(type)) {
//			title = "New Arrivals";
//		} else if (Constant.TYPE_MVP24HRS.equals(type)) {
//			title = "MVP 24hrs";
//		} else if (Constant.TYPE_TOPSELLERS.equals(type)) {
//			title = "Top Sellers";
//		} else if (Constant.TYPE_LATESTDISCOUNT.equals(type)) {
//			title = "Latest Discount";
//		}
//		Intent intent = new Intent(getActivity(), ProductListActivity.class);
//		intent.putExtra(Constant.PRODUCTLIST_TYPE, type);
//		intent.putExtra(Constant.TO_PRODUCTLIST_FROM, Constant.FROM_HOME);
//		intent.putExtra(Constant.PRODUCT_TITLE, title);
//
//		startActivity(intent);
//	}

    /**
     * @创建：Tony 2016-3-28下午3:51:18
     * @描述：过滤模式切换动画
     */
    public void startFilterModeChangeAnima() {
        // rootView.startAnimation(switchFilterAnimation);
        homeScrollView.startAnimation(switchFilterAnimation);
    }

    /**
     * 首页数据刷新入口
     *
     * @param hmModels List<HomeModuleModel> 数据源
     * @param where
     */
    private void refreshHomeUi(List<HomeModuleModel> hmModels, String where) {
        if (null != hmModels) {
            // int messageNum = homeDataModel.getUnReadNoticeCount();
            // homeModuleModels = hmModels;
//			Log.i("KK", "homeModuleModels " + homeModuleModels.size() + "  "
//					+ where);
            for (int i = 0; i < homeModuleModels.size(); i++) {
                HomeModuleModel hmd = homeModuleModels.get(i);
//				Log.i("KK",
//						"HomeModuleModel " + hmd.getName() + " "
//								+ hmd.getModuleType() + "  " + where);
                if (hmd != null) {
                    int modelType = hmd.getModuleType();
                    switch (modelType) {// TODO 后期会根据model动态布局模块位置 返回时数据已经排序
                        case 1:// ActivityList，历史活动
                            refreshActiveData(hmd);
                            break;
                        case 2:// Coupon，优惠券
                            refreshCouponData(hmd);
                            break;
                        case 3:// Advertisement， 功能区
                            refreshAdvertisementData(hmd);
                            break;
                        case 4:// Banner，首页Banner
                            refreshBannerData(hmd);
                            break;
                        default:
                            break;
                    }
                }
            }
        }
    }

    /**
     * 刷新banner数据
     *
     * @param hmd
     */
    private void refreshBannerData(HomeModuleModel hmd) {
        List<ModuleChildrenModel> banners = hmd.getChildren();
        // 判读获取的Banners是否为空
        if (banners != null && 0 < banners.size()) {
            // 已经加载的Banner集合是否为空 不为空先清除在赋值，为空则直接赋值
            if (bannerModels != null) {
                bannerModels.clear();
                bannerModels.add(banners.get(banners.size() - 1));
                bannerModels.addAll(banners);
                bannerModels.add(banners.get(0));
            } else {
                bannerModels = new ArrayList<ModuleChildrenModel>();
                bannerModels.add(banners.get(banners.size() - 1));
                bannerModels.addAll(banners);
                bannerModels.add(banners.get(0));
//				bannerModels = banners;
            }
        } else {
            return;
        }

        if (null == viewPagerFastSelling) {
            return;
        }
        viewPagerFastSelling.setVisibility(View.VISIBLE);
        deflautImage.setVisibility(View.GONE);
        if (null == bannerAdapter) {
            Context mContext = getActivity();
            if (null == mContext) {
                return;
            }
            bannerAdapter = new HomeBannerAdapter(getActivity(), bannerModels,
                    tracker);
            bannerAdapter.setOnLinkBannerClickListenner(this);
            viewPagerFastSelling.setAdapter(bannerAdapter);

            viewPagerFastSelling.setCurrentItem(1, false);
            pageIndicator.setViewPager(viewPagerFastSelling);
            pageIndicator.setOnPageChangeListener(new OnPageChangeListener() {

                @Override
                public void onPageSelected(int arg0) {
                    curretnBannerIndex = arg0;
                    int maxIndex = bannerModels.size() - 1;
                    if (arg0 == 0) {
                        //在原数据前后分别加上最后一条数据 和第一条数据后 当选择第0个时 为了向前滑动有数据
                        //所以将下标变为相同Item的下标记
                        curretnBannerIndex = maxIndex - 1;
                    } else if (arg0 == maxIndex) {
                        curretnBannerIndex = 1;
                    }
                    //currentnBannerIndex 为Banner下标
                    //Baner比点点点多两个 所以点点点的下表需要减去Banner最开始补进的一位
                    pageIndicator.setCurrentItem(curretnBannerIndex - 1);
                }

                @Override
                public void onPageScrolled(int arg0, float arg1, int arg2) {

                }

                @Override
                public void onPageScrollStateChanged(int arg0) {
                    isFilg = ViewPager.SCROLL_STATE_DRAGGING == arg0 ? true
                            : false;
                    if (ViewPager.SCROLL_STATE_IDLE == arg0) {//滚动停止
                        viewPagerFastSelling.setCurrentItem(curretnBannerIndex, false);
                    }
                }
            });
        } else {
            Logger.i(TAG, "NotifyDataSetChanged");
            // bannerAdapter.setBannerModels(bannerModels);
            bannerAdapter.notifyDataSetChanged();
            pageIndicator.notifyDataSetChanged();
            viewPagerFastSelling.setCurrentItem(1, false);

        }
        Logger.i(TAG, "parper" + isFilg + "c " + bannerModels.size());
        if (!isBannerRun) {
            isBannerRun = true;
            bannerHandler.postDelayed(bannerLoopRunnable, LOOP_TIME);
        }
    }

    /**
     * 刷新功能区数据
     *
     * @param hmd
     */
    private void refreshAdvertisementData(HomeModuleModel hmd) {
        List<ModuleChildrenModel> adverts = hmd.getChildren();
        // 判读获取的Banners是否为空
        if (adverts != null && 0 < adverts.size()) {
//			Log.i("FFF", "adverts.size() " + adverts.size());
            // 已经加载的Banner集合是否为空 不为空先清除在赋值，为空则直接赋值
            if (advertModels != null) {
                advertModels.clear();
                advertModels.addAll(adverts);
            } else {
                advertModels = adverts;
            }
        } else {
            return;
        }
        advertAdapter.notifyDataSetChanged();
    }

    /**
     * 刷新Coupon数据
     *
     * @param hmd
     */
    private void refreshCouponData(HomeModuleModel hmd) {
        DisplayImageOptions couponOptions = ImageLoaderUtils.getImageLoaderOptions(
                R.drawable.coupon_index, R.drawable.coupon_index);
        if (null == hmd || hmd.getChildren().size() <= 0) {
            return;
        }
        ModuleChildrenModel mcm = hmd.getChildren().get(0);
        String imageUrl = mcm.getPhoneImg();
        ImageLoader.getInstance().displayImage(imageUrl, couponView, couponOptions);
    }

    /**
     * 刷新活动区域数据
     *
     * @param hmd
     */
    private void refreshActiveData(HomeModuleModel hmd) {
        if (null == hmd) {
            return;
        }
        DisplayImageOptions activeOptions = ImageLoaderUtils.getImageLoaderOptions(
                R.drawable.active_icon, R.drawable.active_icon);
        ModuleChildrenModel mcm = hmd.getChildren().get(0);
        String imageUrl = mcm.getPhoneImg();
        ImageLoader.getInstance().displayImage(imageUrl, activeView, activeOptions);
    }

    @Override
    public void netWorkChangeCallBack(boolean isNetAvaliable) {
        // 表示网络打开
        if (isNetAvaliable && !isDetached() && isAdded()) {
            // 广告无数据重新加载
            if (null == homeModuleModels || homeModuleModels.isEmpty()) {
                AsyncTaskUtil.executeTask(new HomeDataAsyncTask());
            }

            if (null != rootView) {
                if (null != homeModuleModels && !homeModuleModels.isEmpty()
                        && viewPagerFastSelling.getVisibility() == View.GONE) {
                    // processFastSelling();
                    refreshHomeUi(homeModuleModels, "network");
                    getBfdProducts();
                }
            }
        }
    }

    @Override
    public void onAttach(Activity activity) {
        homeActivity = (HomeActivity) activity;
        homeActivity.setTouchEventListenner(this);
        super.onAttach(activity);
    }

    @Override
    public void onTouch(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                Logger.i(TAG, "Down to stop Banner Looper");
                bannerHandler.removeCallbacks(bannerLoopRunnable);
                isBannerRun = false;
                break;

            case MotionEvent.ACTION_UP:
                Logger.i(TAG, "to start " + isBannerRun);
                if (!isBannerRun && null != bannerModels) {
                    isBannerRun = true;
                    Logger.i(TAG, "to start");
                    bannerHandler.postDelayed(bannerLoopRunnable, LOOP_TIME);
                }
        }

    }

    @Override
    public void onStop() {
        isStop = true;
        bannerHandler.removeCallbacks(bannerLoopRunnable);
        isBannerRun = false;
        super.onStop();
    }

    @Override
    public void onClickBanner(ModuleChildrenModel mcModel) {
        // AsyncTaskUtil.executeTask(new BannerDetailAsyncTask(bannerid));
//		Log.i("FFF", "onClickBanner "+mcModel.getActiveType());
        BannerUtils.clickActiv(homeActivity, mcModel, Parmars.GETTYPE_HOMEBANNER, null);
    }

    /**
     * 获取首页缓存数据
     *
     * @author 黄飞
     */
    private class HomeDataCacheTask extends AsyncTask<Void, Void, String> {
        @Override
        protected String doInBackground(Void... params) {
            // ArrayList<BannerModel> localDBCacheList = bannerService
            // .queryAllBanners();
            List<HomeModuleModel> localDBCachehmms = homeModuleDataService
                    .queryModuleDataByModuleType(getActivity(), null);
            if (null != localDBCachehmms && !localDBCachehmms.isEmpty()) {
                homeModuleModels = localDBCachehmms;

            }
            return "0";
        }

        @Override
        protected void onPostExecute(String result) {
            refreshHomeUi(homeModuleModels, "cache");
            AsyncTaskUtil.executeTask(new HomeDataAsyncTask());
//				OkHttpHelper.getOkHttpHelperInstance().asyncGetRequest(Constant.GETHOMEDATA_URL, null, new DxOkHttpCallback(){
//
//					@Override
//					protected void doSomethingTask(Object object) {
//						if(null==object){
//							return ;
//						}
//						Log.i(TAG, "doSomethingTask "+object.toString());
//						// TODO  做耗时的操作 工作在子线程
//						HomeDataModel hdModel=(HomeDataModel) object;
//						if (null != hdModel) {
//							List<HomeModuleModel> hmms = hdModel.getAppHome();
//							if (null != hmms) {
//								homeModuleModels = hmms;
//								Log.i("KK", "hmms size: " + hmms.size());
//								homeModuleDataService.clearHomeModuleData();
//								homeModuleDataService.batchInsertDataByTransaction(hmms);
//							}
////							int unReadMsg=hdModel.getUnReadNoticeCount();
////							StringUtil.saveConfig(ServerConstant.MessageCenter.UNREAD_MESSAGE, unReadMsg+"");
//						}
//					}
//
//					@Override
//					protected Object parserBeanTask(String status,
//							JSONObject response) {
//						if(null==response){
//							return null;
//						}
//						Log.i(TAG, "parserBeanTask status: "+status+" "+response.toString());
//						JSONObject dataObject = response.optJSONObject(Constant.JSON_DATA);
//						HomeDataModel homeData=JsonUtils.fromJson(dataObject.toString(),HomeDataModel.class);
//						return homeData;
//					}
//
//					@Override
//					protected void onTaskFinish(String result, Object object) {
//						// TODO 刷新 UI 工作在主线程
//						if("0".equals(result)){
//							if(null==object){
//								return;
//							}
//							Log.i(TAG, "parserBeanTask status: "+result+" "+object.toString());
//							HomeDataModel hdModel=(HomeDataModel) object;
//							homeScrollView.onRefreshComplete();
//							if ("0".equals(result)) {
//								if (null != hdModel) {
////									int unReadMsg=hdModel.getUnReadNoticeCount();
////									setMessageState(unReadMsg);
//									refreshHomeUi(hdModel.getAppHome(), "task");
//								} 
//							}
//						}else{
//							
//						}
//						
//					}});
            super.onPostExecute(result);
        }
    }

    /**
     * 获取首页轮转banner、功能区域 、Coupon、Active数据
     *
     * @author hf
     * @version [版本号, 2016-4-12]
     * @see [相关类/方法]
     * @since [产品/模块版本]
     */
    private class HomeDataAsyncTask extends AsyncTask<Void, Void, String> {

        // public HomeDataAsyncTask(String bannerId) {
        // }
        private HomeDataModel hdModel;

        @Override
        protected void onPreExecute() {
        }

        @Override
        protected String doInBackground(Void... params) {

            try {
                hdModel = ProviderFactory.createMainServiceProvider()
                        .getHomeData(String.valueOf(Common.getAppVersion(getActivity())));
            } catch (DxException e) {
                return e.getErrCode();
            }

            if (null != hdModel) {
                List<HomeModuleModel> hmms = hdModel.getAppHome();
                if (null != hmms) {
                    homeModuleModels = hmms;
                    homeModuleDataService.clearHomeModuleData();
                    homeModuleDataService.batchInsertDataByTransaction(hmms);
                }
//				int unReadMsg=hdModel.getUnReadNoticeCount();
//				StringUtil.saveConfig(ServerConstant.MessageCenter.UNREAD_MESSAGE, unReadMsg+"");
            }

            return "0";
        }

        @Override
        protected void onPostExecute(String result) {
            if (isAdded()) {
                homeScrollView.onRefreshComplete();
                if ("0".equals(result)) {
                    if (null != hdModel) {
//						int unReadMsg=hdModel.getUnReadNoticeCount();
//						setMessageState(unReadMsg);
                        refreshHomeUi(hdModel.getAppHome(), "task");
                    }
                } else {
                    AlertToast.alert(getActivity(),
                            ServerConstant.ReturnCode.MESSAGEMAP.get(result));
                }
            }
        }
    }

    @Override
    public void notifyMessageChange(int newMsgNum, int msgType) {
        setMessageState(newMsgNum);
    }

    /**
     * @param mBfdProducts
     * @创建：Tony 2016-5-13下午2:35:44
     * @描述：将获取的
     */
    private void saveRecommendProducts2LocalData(final ArrayList<ProductModel> mBfdProducts) {
        ProductService productDBProvider = ProviderFactory.createProductDBProvider();
        productDBProvider.deleteProductListByType(ProductService.TYPE_BFD_HOME);
        for (int i = 0; i < mBfdProducts.size(); i++) {
            productDBProvider.saveProductInfo(mBfdProducts.get(i), ProductService.TYPE_BFD_HOME);
        }
    }
}
